package com.school.service.impl;

import com.school.dao.ClassRoomDao;
import com.school.dao.ClassesDao;
import com.school.dao.CourseSelectDao;
import com.school.dao.GradeDao;
import com.school.dao.impl.*;
import com.school.domain.*;
import com.school.service.StudentService;

import java.util.ArrayList;
import java.util.List;

public class StudentServiceImpl implements StudentService {
    private final StudentDaoImpl studentDao = new StudentDaoImpl();
    private final CourseDaoImpl courseDao = new CourseDaoImpl();
    private final CourseSelectDao courseSelectDao = new CourseSelectDaoImpl();
    private final GradeDao gradeDao = new GradeDaoImpl();
    private final ClassRoomDao classRoomDao = new ClassRoomDaoImpl();


    @Override
    public boolean studentLogin(long sid, String pwd) {
        Student student = studentDao.findById(sid);
        return student != null && student.getPwd().equals(pwd);
    }

    @Override
    public boolean update(Student student) {
        return studentDao.update(student);
    }

    @Override
    public Student find(long sid) {
        return studentDao.findById(sid);
    }

    @Override
    public List<Course> findCourses(long sid) {
        List<CourseSelection> courseSelectionList = courseSelectDao.findBySid(sid);
        ArrayList<Course> courses = new ArrayList<>();
        for (CourseSelection courseSelection : courseSelectionList) {
            courses.add(courseDao.findById(courseSelection.getCoid()));
        }
        return courses;
    }

    @Override
    public List<Grade> findGrand(long sid) {
        return gradeDao.findBySid(sid);
    }

    @Override
    public boolean choseCourse(long sid, long coid) {
        Course course = courseDao.findById(coid);
        if (course != null && courseSelectDao.add(new CourseSelection(0, sid, coid))) {
            course.setNowNum(course.getNowNum()+1);
            return courseDao.update(course);
        }
        return false;
    }

    @Override
    public boolean choseClassRoom(Student student, long rid) {
        ClassRoom classRoom = classRoomDao.findById(rid);
        // 没有此教室或没座位
        if (classRoom == null || classRoom.getNowNum() == classRoom.getNum()) return false;
        student.setRid(rid);
        classRoom.setNowNum(classRoom.getNowNum()+1);
        return studentDao.update(student) && classRoomDao.update(classRoom);
    }

    @Override
    public List<Course> findAllCourses() {
        return courseDao.findAll();
    }


    @Override
    public ClassRoom findClassRoom(long rid) {
        return classRoomDao.findById(rid);
    }

    @Override
    public List<Student> findClassMates(long clid) {
        return studentDao.findByClid(clid);
    }
}
